#!/usr/bin/env python
# coding: utf-8
import random
import time
import configparser
import os
import subprocess
import logging
import platform

from config.settings import CONFIG_PATH, APPIUM_LOG_PATH

logger = logging.getLogger('train')


def find_device(device):
    """检查可用设备"""
    logger.info('开始寻找设备')
    # 查询所有可用设备
    cf = configparser.ConfigParser()
    config_path = CONFIG_PATH + '/device.ini'
    cf.read(config_path)

    try:
        return dict(cf.items(device))
    except configparser.NoSectionError:
        raise configparser.NoSectionError('没有%s的设备，请检查device.ini文件' % device)


def start_appium_server(build_tag):
    """
    启动appium服务
    :return:
    """
    # 通过端口号杀掉appium服务
    sys_platform = platform.system()
    appium_log = APPIUM_LOG_PATH + '/appium_' + build_tag + '.log'  # appium日志名称
    logger.info('生成appium日志，日志名称：%s' %appium_log)
    # 启动appium服务
    port = random.randint(4000, 4999)
    bport = port + 1
    if sys_platform == "Windows":
        start_server = "node C:/Users/weixin.yuan/AppData/Local/Programs/appium-desktop" \
                       "/resources/app/node_modules/appium/build/lib/main.js " \
                       " -p %s -bp %s " \
                       "--session-override --command-timeout 20000 " \
                       "--debug-log-spacing --no-reset " \
                       "--log-timestamp --local-timezone > %s" % (str(port), str(bport), appium_log)
    else:
        start_server = "node /Applications/Appium.app/Contents/Resources/app/node_modules/appium/build/lib/main.js " \
                       " -p %s -bp %s " \
                       "--session-override --command-timeout 20000 " \
                       "--debug-log-spacing --no-reset " \
                       "--log-timestamp --local-timezone > %s" % (str(port), str(bport), appium_log)

    try:
        logger.info('appium启动命令：%s' % start_server)
        rs = subprocess.Popen(start_server, shell=True)
        logger.info(rs)
    except Exception as e:
        logger.error('启动appium服务发送错误，错误信息：%s' % str(e))
        raise Exception('启动appium服务失败，请联系工程自动化测试人员')
    time.sleep(10)
    return port


def kill_appium_server(port):
    sys_platform = platform.system()
    if sys_platform == "Windows":
        kill_server = "taskkill /f /t /im node.exe"
    else:
        kill_server = "lsof -i:%s | grep node | awk '{print $2}' | sed -n '1P' | xargs kill -9 " % port
        logger.info("杀掉占用%s端口的appium服务" % port)
    logger.info(kill_server)
    os.system(kill_server)


def start_wda_server():
    os.system("security unlock-keychain -p tzmm.987 ~/Library/Keychains/login.keychain")
    udid = os.popen("idevice_id -l | head -n1").read()
    logger.info("udid=" + udid)
    if not udid:
        raise Exception("没有找到设备，请确认设备是否连接正常。")
    udid = udid.replace('\n', '').replace('\r', '')
    cmd = 'xcodebuild -project /Applications/Appium.app/Contents/' \
          'Resources/app/node_modules/appium/node_modules/' \
          'appium-xcuitest-driver/WebDriverAgent/WebDriverAgent.xcodeproj ' \
          '-scheme WebDriverAgentRunner -destination "id=%s" test' % udid
    logger.info('启动xcode命令：' + cmd)
    subprocess.Popen(cmd, shell=True)
    subprocess.Popen("iproxy 8100 8100 %s" % udid, shell=True)


if __name__ == "__main__":
    pass